//
//  ChatViewController.swift
//  chenChat
//
//  Created by chen on 16/2/17.
//  Copyright © 2016年 chen. All rights reserved.
//

import UIKit
import SnapKit

class ChatViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,FHInputToolbarDelegate {
    var tableView: UITableView = UITableView()
    var tableSource: NSMutableArray = []
    //当前输入框的高度
    var textHeigth: CGFloat = 0.0
    var friend: UserInfo = UserInfo(id: "1", name: "lucy")
    var lordUser: UserInfo = UserInfo(id: "0", name: "chen")
    var inputToolbar: FHInputToobar = FHInputToobar(frame: CGRect(x: 0, y: UIScreen.mainScreen().bounds.height - 44 , width: UIScreen.mainScreen().bounds.width, height: 44))
    //原始的输入框的坐标位移
    var originalinputToolbar: CGRect = CGRect(x: 0, y: 0, width: 0, height: 0)
    override func viewDidLoad() {
        super.viewDidLoad()
        //原始坐标位移
        self.originalinputToolbar = self.inputToolbar.frame
        //背景图片
        let backgroundImageView = UIImageView(image: UIImage(named: "chat_bg_default.jpg"))
        self.view.addSubview(backgroundImageView)
        self.tableView.dataSource = self
        self.tableView.delegate = self
        self.tableView.registerClass(MessageCell.self, forCellReuseIdentifier: MessageCell.reuseIdentifier())
        let viewWidth = self.view.frame.width
        let viewHeight = self.view.frame.height
        self.tableView.frame = CGRectMake(0, 60, viewWidth, viewHeight)
        //第一个cell空出来的空间
        let headerView = UIView()
        headerView.frame = CGRectMake(0, 0, tableView.frame.width, 10)
        headerView.backgroundColor = UIColor.clearColor()
        self.tableView.tableHeaderView = headerView
        
        self.tableView.separatorStyle = .None
        self.tableView.backgroundColor = UIColor.clearColor()
        self.view.addSubview(tableView)
        self.inputToolbar.delegate = self
        textHeigth = self.inputToolbar.frame.height
        self.view.addSubview(inputToolbar)
        
        //navigationbar的title
//        self.setupNavigationTitle(self.friend.name!)
        
        //keyboard notitication
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardFrameWillChange:", name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardFrameWillHide:", name: UIKeyboardWillHideNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewFrameWillChange:", name: UITextViewTextDidChangeNotification, object: nil)
        //keyboard收回加入点击事件。
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "handleTouches:")
        tapGestureRecognizer.cancelsTouchesInView = false
        self.view.addGestureRecognizer(tapGestureRecognizer)
        
        //tableSource的数据加载
        let message1: Message = Message(incoming: false, message: "你是谁啊？？", sentDate: NSDate())
        let message2: Message = Message(incoming: true, message: "你是谁啊？？", sentDate: NSDate())
        let message3: Message = Message(incoming: true, message: "你是谁啊？？", sentDate: NSDate())
        let message4: Message = Message(incoming: false, message: "你是谁啊你是谁啊你是谁啊你是谁啊你是谁啊你是谁啊你是谁啊你是谁啊你是谁啊你是谁啊你是谁啊你是谁啊你是谁啊？？", sentDate: NSDate())
        self.tableSource.addObjectsFromArray([message1,message2,message3,message4])
        
    }
    func chatFriendDidChange(user: UserInfo){
        let name = user.name
        self.setupNavigationTitle(name!)
       
    }
    func setupNavigationTitle(name: String){
        let titleLabel = UILabel(frame: CGRect(x: 50, y: 0, width: 220, height: 44))
        titleLabel.text = name
        titleLabel.textColor = UIColor.grayColor()
        titleLabel.textAlignment = .Center
        titleLabel.backgroundColor = UIColor.clearColor()
        titleLabel.font = UIFont.systemFontOfSize(18)
        self.navigationItem.title = name
        
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.tableSource.count
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return MessageCell.heightForCell(self.tableSource.objectAtIndex(indexPath.row) as! Message)
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(MessageCell.reuseIdentifier()) as! MessageCell
        cell.selectionStyle = .None
        cell.setupFriendCell(tableSource.objectAtIndex(indexPath.row) as! Message, user: self.lordUser)

        return cell
    }
    func textViewFrameWillChange(notify: NSNotification){
        //这是TextView的高度
        let height = self.inputToolbar.textField.contentSize.height
        //如果TextView的高度改变了，那么inputToolbar的坐标，高度也要改变，背景图片也要改变高度，textViewground也要改变高度
        //这里有必要是有SnipKit进行边缘关联
        if height > textHeigth{
            UIView.animateWithDuration(0.1, animations: { () -> Void in
                let textFieldFrame = self.inputToolbar.frame
                
                //这里是改变inputToolbar的位移坐标
                self.inputToolbar.frame = CGRectMake(0, textFieldFrame.origin.y - 10 , UIScreen.mainScreen().bounds.width, textFieldFrame.height + 10)
                self.inputToolbar.backgroundImageView.frame = CGRectMake(0, 0, self.inputToolbar.frame.width, self.inputToolbar.frame.height + 10)
                self.inputToolbar.textFieldBackground.frame = CGRectMake(44, 0, UIScreen.mainScreen().bounds.width - 34 - 10 - 34 - 10, self.inputToolbar.frame.height + 5)
                self.inputToolbar.textField.frame = CGRectMake(44, 0, self.inputToolbar.textFieldBackground.frame.width, self.inputToolbar.frame.height + 5)
                //这里还需要改变tableview的位移坐标
                self.tableView.frame = CGRectMake(0, 60, self.view.frame.width, self.tableView.bounds.height - 5)
                
                }) { (Bool) -> Void in
                    //这里还需要改变tableview的位置坐标才行。要不然它scrollposition还是在原有的基础上进行滑动的，也就不会改变了
                    
                    //这里需要对tableview的布局，位移进行设置
                    let path: NSIndexPath = NSIndexPath(forRow: self.tableSource.count-1, inSection: 0)
                    self.tableView.scrollToRowAtIndexPath(path, atScrollPosition: .Bottom, animated: false)
            }
            self.textHeigth = height
        }
        
    }
    func keyboardFrameWillChange(notify: NSNotification){
        //获取当前的通知信息
        let userInfo = notify.userInfo!
        //取出通知信息中的键盘动态延迟变量
        let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
        //取出通知信息中键盘移动位移
        let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //
//        var deltaY = keyboardFrame.size.height

        UIView.animateWithDuration(duration, animations: { () -> Void in
            let viewWidth = self.view.frame.width
            let viewHight = self.view.frame.height
            //这个60应该是给navigation预留出来的空间
            self.tableView.frame = CGRectMake(0, 60, viewWidth, viewHight - 60 - self.inputToolbar.frame.height - keyboardFrame.height)
            //位置移动
//            self.inputToolbar.transform = CGAffineTransformMakeTranslation(0,-deltaY)
            self.inputToolbar.frame = CGRectMake(0, UIScreen.mainScreen().bounds.height - 44 - keyboardFrame.height, UIScreen.mainScreen().bounds.width, 44)
            }) { (Bool) -> Void in
                
                //nsindexpath是tableview的最后一行，
                let path: NSIndexPath = NSIndexPath(forRow:self.tableSource.count - 1, inSection: 0)
                self.tableView.scrollToRowAtIndexPath(path, atScrollPosition: .Bottom, animated: false)
        }
        //给原始坐标赋值
        self.originalinputToolbar = self.inputToolbar.frame
    }
    func keyboardFrameWillHide(notify: NSNotification){
        let userInfo = notify.userInfo!
        let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
        
        UIView.animateWithDuration(duration, animations: { () -> Void in
            let viewWidth = self.view.frame.width
            let viewHight = self.view.frame.height
            self.tableView.frame = CGRectMake(0, 60, viewWidth, viewHight - 60 - self.inputToolbar.frame.height)
            self.inputToolbar.frame = CGRectMake(0, UIScreen.mainScreen().bounds.height - 44, UIScreen.mainScreen().bounds.width, 44)
            })
    }
    func handleTouches(sender: UITapGestureRecognizer){
        self.inputToolbar.textField.resignFirstResponder()
    }
    func onInputBtnTapped(text: String) {
        if text.isEmpty {
            return
        }
        let message: Message = Message(incoming: true, message: text, sentDate: NSDate())
        self.tableSource.addObject(message)
        self.tableView.reloadData()
        
        let path: NSIndexPath = NSIndexPath(forRow:tableSource.count - 1, inSection: 0)
        self.tableView.scrollToRowAtIndexPath(path, atScrollPosition: .Bottom, animated: true)
        self.clearconstaints()
    }
    func onLeftBtnTapped(text: String) {
        if text.isEmpty {
            return
        }
        let message: Message = Message(incoming: false, message: text, sentDate: NSDate())
        self.tableSource.addObject(message)
        self.tableView.reloadData()
        
        let path: NSIndexPath = NSIndexPath(forRow:tableSource.count - 1, inSection: 0)
        self.tableView.scrollToRowAtIndexPath(path, atScrollPosition: .Bottom, animated: true)
        self.clearconstaints()
    }
    func clearconstaints(){
        UIView.animateWithDuration(0.3, animations: { () -> Void in
            let textFieldFrame = self.originalinputToolbar
            self.inputToolbar.frame = CGRectMake(0, textFieldFrame.origin.y  , UIScreen.mainScreen().bounds.width, textFieldFrame.height)
            self.inputToolbar.backgroundImageView.frame = CGRectMake(0, 0, self.inputToolbar.frame.width, self.inputToolbar.frame.height)
            self.inputToolbar.textFieldBackground.frame = CGRectMake(44, 0, UIScreen.mainScreen().bounds.width - 34 - 10 - 34 - 10, self.inputToolbar.frame.height)
            self.inputToolbar.textField.frame = CGRectMake(44, 0, self.inputToolbar.textFieldBackground.frame.width, self.inputToolbar.frame.height)
            })
    }
    



}
